package com.itheima.service;

import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.itheima.common.HttpUtils;
import com.itheima.domain.User;
import com.itheima.mapper.UserDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Map;

@Service
public class UserService {

    @Autowired(required = false)
    private UserDao userDao;

    @Value("${wx.appid}")
    private String appid;
    @Value("${wx.secret}")
    private String secret;
    @Value("${wx.accessTokenUrl}")
    private String accessTokenUrl;
    @Value("${wx.wxInfoUrl}")
    private String wxInfoUrl;

    public User wxLogin(String code) {

        User user = null;
        //1.根据code获取access_token和openId
        String atUtl = accessTokenUrl + "?code="+code+"&appid="+appid+"&secret="+secret+"&grant_type=authorization_code";
        System.out.println(atUtl);
        Map<String, Object> map1 = HttpUtils.sendGet(atUtl);
        Object access_token = map1.get("access_token");
        Object openid = map1.get("openid").toString();
        if(access_token == null && openid == null) {
            return user;
        }

        //2.根据openId判断用户是否存在
        user = userDao.findByOpenid(openid.toString());
        if(user != null) {
            System.out.println("返回数据库中的用户对象");
            //3.如果用户存在返回用户信息
            return user;
        }else{
            System.out.println("查询微信数据库");
            //4.如果用户不存在，根据access_token和openId获取微信用户信息
            String wxurl = wxInfoUrl + "?access_token=" + access_token +"&openid="+openid;
            Map<String, Object> map2 = HttpUtils.sendGet(wxurl);
            Object nickname = map2.get("nickname");
            Object headimgurl = map2.get("headimgurl");
            if(nickname == null || headimgurl == null) {
                return user;	//用户为空返回登入失败
            }

            //5.将微信用户信息保存到数据库，返回用户数据
            user = new User();
            //user.setId( idWorker.nextId()+"" ); 自动生成
            user.setRegdate(new Date());//注册日期
            user.setUpdatedate(new Date());//最后修改日期
            user.setLastdate(new Date());//最后登陆日期
            user.setOnline(0L);//登陆时长
            user.setFanscount(0);//粉丝数
            user.setFollowcount(0);//关注数
            user.setOpenid(openid.toString());
            user.setNickname(nickname.toString());
            user.setAvatar(headimgurl.toString());
            userDao.insert(user);
        }
        return user;		//保存用户返回用户信息
    }
}
